package top.syfy.bili.fbm.gui;

import top.syfy.bili.fbm.util.FfmpegUtil;
import top.syfy.bili.fbm.util.JSONAttributeUtil;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import java.awt.Font;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.GridLayout;
import java.io.File;
import java.io.IOException;
import java.util.Objects;

/**
 * GUI视图
 *
 * @author awg
 * @date 2020/10/20 星期二
 */
public class MainGUI extends JFrame {

    private static final long serialVersionUID = 1L;

    /**
     * 文件选择器的起始选择路径
     */
    private static final String DEFAULT_DIR_PATH = System.getProperty("user.home");

    private static final Font font = new Font(Font.DIALOG, Font.BOLD, 18);

    public static void main(String[] args) {
        MainGUI gui = new MainGUI();
        gui.setLayout(new GridLayout(6, 4, 10, 20));
        gui.setSize(1000, 600);
        gui.setLocationRelativeTo(null);

        JPanel ffmpegPanel, inPathPanel, outPathPanel;
        ffmpegPanel = showPathPanel(gui, "ffmpeg可执行文件（点击右侧按钮进行选择）", "选择文件", JFileChooser.FILES_ONLY);
        inPathPanel = showPathPanel(gui, "专辑存放目录（点击右侧按钮进行选择）", "选择目录", JFileChooser.DIRECTORIES_ONLY);
        outPathPanel = showPathPanel(gui, "输出存放目录（点击右侧按钮进行选择）", "选择目录", JFileChooser.DIRECTORIES_ONLY);

        JButton loadBtn = new JButton("开始");
        loadBtn.setCursor(new Cursor(Cursor.HAND_CURSOR));
        loadBtn.addActionListener(e -> {
            //获取输入框中的值
            String ffmpegText = getTextFromTextField(getTextFieldFromPanel(ffmpegPanel));
            String inPathText = getTextFromTextField(getTextFieldFromPanel(inPathPanel));
            String outPathText = getTextFromTextField(getTextFieldFromPanel(outPathPanel));

            //选择的文件、目录
            if ("".equals(ffmpegText) || "".equals(inPathText) || "".equals(outPathText)) {
                JOptionPane.showMessageDialog(gui, "缺少必要的参数，请检查【ffmpeg可执行文件所在的目录、专辑存放目录、输出存放目录】是否已选择", "消息", JOptionPane.ERROR_MESSAGE);
                return;
            }

            try {
                //合并过程中，禁止按钮点击
                loadBtn.setText("合并中...");
                loadBtn.setEnabled(false);
                //合并文件
                FfmpegUtil.runFfmpeg(ffmpegText, JSONAttributeUtil.parseCacheDir(new File(inPathText)), new File(outPathText));
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
            loadBtn.setEnabled(true);
            loadBtn.setText("执行");
            JOptionPane.showMessageDialog(gui, "合并完成", "消息", JOptionPane.INFORMATION_MESSAGE);
        });

        JPanel tipsPanel = new JPanel();
        tipsPanel.setLayout(new BorderLayout());
        JLabel tips = new JLabel("【注】：修改 bilicachevideo.properties 配置文件之后，请手动重启软件");
        tips.setFont(font);
        tips.setForeground(Color.RED);
        tipsPanel.add(tips, BorderLayout.CENTER);

        gui.add(loadBtn);
        gui.add(tipsPanel);
        gui.setDefaultCloseOperation(EXIT_ON_CLOSE);
        gui.setResizable(false);
        gui.setVisible(true);
    }

    /**
     * 从JTextField中获取值
     *
     * @param textField 输入框
     * @return 输入框中的值
     */
    private static String getTextFromTextField(JTextField textField) {
        return Objects.requireNonNull(textField).getText().trim();
    }

    /**
     * 从JPanel组件中获取JTextField子组件
     *
     * @param panel JPanel组件
     * @return JJPanel组件中的JTextField子组件
     */
    private static JTextField getTextFieldFromPanel(JPanel panel) {
        Component[] components = panel.getComponents();
        for (Component c : components) {
            if (Objects.nonNull(c) && (c instanceof JTextField)) {
                return (JTextField) c;
            }
        }
        return null;
    }

    /**
     * 设置【ffmpeg可执行文件】、【专辑存放目录】、【输出存放目录】
     *
     * @param frame             JFrame窗体
     * @param textFieldHint     属性值输入框文本提示
     * @param btnHint           按钮文本提示
     * @param fileSelectionMode 文件选择器的模式（仅文件、仅目录）
     */
    private static JPanel showPathPanel(JFrame frame, String textFieldHint, String btnHint, int fileSelectionMode) {
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        JLabel hint = new JLabel(textFieldHint);
        hint.setFont(font);
        JTextField textField = new JTextField();
        textField.setEditable(false);
        JButton button = new JButton(btnHint);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));
        button.addActionListener(e -> {
            JFileChooser chooser = new JFileChooser(DEFAULT_DIR_PATH);
            // 选择输出存放目录
            chooser.setFileSelectionMode(fileSelectionMode);
            int val = chooser.showOpenDialog(null);    //文件打开对话框
            if (val == JFileChooser.APPROVE_OPTION) {
                //正常选择文件
                textField.setText(chooser.getSelectedFile().toString());
            }
        });
        panel.add(hint, BorderLayout.NORTH);
        panel.add(textField, BorderLayout.CENTER);
        panel.add(button, BorderLayout.EAST);
        frame.add(panel);
        return panel;
    }

}
